package com.joesem.sale.client.logic.workOrder.option

import android.os.Bundle
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.CheckBox
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.KeyboardUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.FragmentProductListBinding
import com.joesem.sale.client.base.*
import com.joesem.sale.client.logic.workOrder.option.viewModel.ProductViewModel
import com.joesem.sale.client.network.data.ProductMode
import com.joesem.sale.client.utils.click


class ProductListDialog : BaseFragment<FragmentProductListBinding>() {
    companion object {
        var productSelected: (List<ProductMode>) -> Unit = {}
    }

    private val selectedList = mutableListOf<ProductMode>()

    private val listAdapter =
        object : BaseQuickAdapter<ProductMode, BaseViewHolder>(R.layout.item_product) {
            override fun convert(holder: BaseViewHolder, item: ProductMode) {
                val check = holder.getView<CheckBox>(R.id.rbCheck)
                check.visible()
                check.isChecked = selectedList.find { it.id == item.id } != null
                check.click {
                    val isUnSelected = selectedList.find { it.id == item.id } == null
                    if (isUnSelected)
                        selectedList.add(item)
                    else {
                        selectedList.removeAll { it.id == item.id }
                    }
                    notifyDataSetChanged()
                }
                holder.setText(R.id.tvCustomerName, item.name)
                holder.setText(R.id.tvCustomerTelephone, "产品编号：${item.product_number}")
                holder.setText(R.id.tvCustomerUsername, "产品类型：${item.model}")
                holder.setText(R.id.tvCustomerUserAddress, item.customer?.name.orEmpty())
                holder.itemView.click {
                    val isUnSelected = selectedList.find { it.id == item.id } == null
                    if (isUnSelected)
                        selectedList.add(item)
                    else {
                        selectedList.removeAll { it.id == item.id }
                    }
                    notifyDataSetChanged()
                }
            }
        }

    private val viewMode by createViewModel<ProductViewModel>()

    override fun FragmentProductListBinding.initView(savedInstanceState: Bundle?) {
        rvProductList.adapter = listAdapter

        arguments?.getParcelableArrayList<ProductMode>("defaultList")?.apply {
            selectedList.addAll(this)
            listAdapter.notifyDataSetChanged()
        }
    }

    override fun FragmentProductListBinding.initListener() {
        vTop.click { requireActivity().onBackPressed() }
        root.click { }

        btnClose.click {
            requireActivity().onBackPressed()
        }
        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onCreate(owner: LifecycleOwner) {
                srlListRefresh.autoRefresh()
            }

            override fun onResume(owner: LifecycleOwner) {
                showAnimation(root)
            }

            override fun onStop(owner: LifecycleOwner) {
                root.setBackgroundColor(R.color.white.color())
            }
        })
        srlListRefresh.apply {
            val customerId = arguments?.getInt("customerId", -1)
            setOnRefreshListener {
                viewMode.getProductList(customerId = customerId?.toString(), isFirstPage = true)
            }
            setOnLoadMoreListener {
                viewMode.getProductList(customerId = customerId?.toString(), isFirstPage = false)
            }
        }
        btnReset.click {
            selectedList.clear()
            listAdapter.notifyDataSetChanged()
        }
        btnConfirm.click {
            if (selectedList.isEmpty()) {
                toast("请选择至少一个商品~")
            } else {
                productSelected.invoke(selectedList)
                requireActivity().onBackPressed()
            }
        }
    }

    override fun FragmentProductListBinding.initIntent(intent: Any?) {
        when (intent) {
            is ProductViewModel.ListIntent -> {
                srlListRefresh.finishRefresh()
                srlListRefresh.finishLoadMore()
                if (intent.isFirst) {
                    listAdapter.setList(intent.data)
                    if (listAdapter.data.isEmpty()) {
                        listAdapter.setEmptyView(R.layout.layout_empty)
                    }
                } else {
                    listAdapter.addData(intent.data)
                }
            }
        }
    }
}

fun optionProduct(
    contentViewId: Int,
    fm: FragmentManager,
    customerId: Int?,
    default: ArrayList<ProductMode>,
    productSelected: (List<ProductMode>) -> Unit
) {
    ProductListDialog.productSelected = productSelected
    fm.beginTransaction().setCustomAnimations(
        R.anim.slide_in_bottom,
        R.anim.slide_out_bottom,
        R.anim.slide_in_bottom,
        R.anim.slide_out_bottom,
    ).replace(
        contentViewId,
        BaseFragment.newInstance<ProductListDialog>(Bundle().apply {
            putParcelableArrayList(
                "defaultList",
                default
            )
            putInt("customerId", customerId ?: -1)
        })
    ).addToBackStack(null).commit()
}
